﻿package command {
	import flash.text.TextField;
	import flash.text.TextFormat;
	
	public class RuDoCommand {
		private var inputField:TextField;
		private var undoList:Array;
		private var redoList:Array;
		
		public function RuDoCommand(inputField:TextField):void {
			this.inputField = inputField;
			undoList = new Array();
			redoList = new Array();
		}
		
		public function addText(index:int, text:String, tf:TextFormat):void {
			addCommand(new AddCommand(inputField, index, text, tf));
		}
		public function delText(index:int, text:String, tf:TextFormat):void {
			addCommand(new DeleteCommand(inputField, index, text, tf));
		}
		public function addReplace(text:String, block:Array, format:Array):void {
			addCommand(new ReplaceCommand(inputField, text, block, format));
		}
		public function alignParagraph(index:Array, align:Array, newAlign:String):void {
			addCommand(new AlignCommand(inputField, index, align, newAlign));
		}
		public function newText(text:String):void {
			addCommand(new NewCommand(inputField, text));
		}
		public function formatSelect(block:Array, oldFormat:Array, newFormat:Array):void {
			addCommand(new FormatSelectCommand(inputField, block, oldFormat, newFormat));
		}
		
		private function addCommand(cmd:ICommand):void {
			//超过Config.RUDO_STEP限额则自动出队列一个
			if (undoList.length > Config.RUDO_STEP) {
				undoList.shift();
			}
			//每添加一次命令，清空redolist
			if(redoList.length) {
				redoList = new Array();
			}
			undoList.push(cmd);
		}
		
		public function undo():Boolean {
			//undoList中有命令则执行，并将相应命令出栈存入redoList中
			if(undoList.length) {
				var cmd:ICommand = undoList.pop() as ICommand;
				cmd.undo();
				redoList.push(cmd);
				return true;
			}
			else {
				return false;
			}
		}
		public function redo():Boolean {
			//redoList中有命令则执行，并将相应命令出栈存入undoList中
			if (redoList.length) {
				var cmd:ICommand = redoList.pop() as ICommand;
				cmd.redo();
				undoList.push(cmd);
				return true;
			}
			else {
				return false;
			}
		}
		
		public function clear():void {
			undoList = new Array();
			redoList = new Array();
		}
	}
}